package com.dog.basics.service.mtkj.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.mtkj.ShopOrderFromDto;
import com.dog.basics.bean.dto.api.mtkj.*;
import com.dog.basics.bean.model.common.DogUser;
import com.dog.basics.bean.model.common.DogUserConnect;
import com.dog.basics.bean.model.mtkj.*;
import com.dog.basics.bean.vo.admin.mtkj.AdminOrderGoodsVo;
import com.dog.basics.bean.vo.admin.mtkj.AdminShopOrderXqVo;
import com.dog.basics.bean.vo.admin.mtkj.AdminUserAddrOrderVo;
import com.dog.basics.bean.vo.admin.mtkj.ShopOrderVo;
import com.dog.basics.bean.vo.api.mtkj.*;
import com.dog.basics.common.util.Json;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.common.util.ToolUtil;
import com.dog.basics.common.util.serialNumberUtils;
import com.dog.basics.dao.common.DogUserConnectMapper;
import com.dog.basics.dao.common.DogUserMapper;
import com.dog.basics.dao.mtkj.*;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.common.WeChatMiniService;
import com.dog.basics.service.mtkj.IMtOrderService;
import com.dog.basics.service.sys.MobileService;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author wph
 * @since 2020-11-09
 */
@Service
@AllArgsConstructor
public class MtOrderServiceImpl extends ServiceImpl<MtOrderMapper, MtOrder> implements IMtOrderService {
    private final WeChatMiniService weChatMiniService;
    private final MtShoppingAccountMapper mtShoppingAccountMapper;
    private final MtFlowingWaterMapper mtFlowingWaterMapper;
    private final MtOrderGoodsMapper mtOrderGoodsMapper;
    private final MtGoodsMapper mtGoodsMapper;
    private final MtGoodsSkuMapper mtGoodsSkuMapper;
    private final MtCouponMapper mtCouponMapper;
    private final DogUserConnectMapper dogUserConnectMapper;
    private final MtUserAddrMapper mtUserAddrMapper;
    private final MtUserAddrOrderMapper mtUserAddrOrderMapper;
    private final MtBasketMapper mtBasketMapper;
    private final MtShoppingMapper mtShoppingMapper;
    private final DogUserMapper dogUserMapper;
    private final MobileService mobileService;
    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param userIds
     */
    public List<Long> getuserIdsWhere(String name, String mobile, List<Long> userIds) {
        List<Long> collect = dogUserMapper.selectList(Wrappers.<DogUser>lambdaQuery().like(StrUtil.isNotBlank(mobile), DogUser::getUserMobile, mobile).like(StrUtil.isNotBlank(name), DogUser::getNickName, name)).stream().map(e -> e.getUserId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            userIds = collect;
        } else {
            userIds.add(-2L);
        }
        return userIds;
    }

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param shopIds
     */
    public List<Long> getshopIdsWhere(String name, List<Long> shopIds) {
        List<Long> collect = mtShoppingMapper.selectList(Wrappers.<MtShopping>lambdaQuery().like(StrUtil.isNotBlank(name), MtShopping::getName, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            shopIds = collect;
        } else {
            shopIds.add(-2L);
        }
        return shopIds;
    }

    /**
     * @Description: 分页订单列表(pc)
     * @Param: OrderFromDto
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<ShopOrderVo> getPageList(PageParam page, ShopOrderFromDto obj) {
        // 判断所属用户ID
        List<Long> userIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getUserName()) || StrUtil.isNotBlank(obj.getMobile())) {
            userIds = getuserIdsWhere(obj.getUserName(), obj.getMobile(), userIds);
        }
        // 判断所属店铺ID
        List<Long> shopIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getShopName())) {
            shopIds = getshopIdsWhere(obj.getShopName(), shopIds);
        }
        IPage iPage = this.page(page, Wrappers.<MtOrder>lambdaQuery()
                .in(CollUtil.isNotEmpty(shopIds), MtOrder::getShopId, shopIds)
                .in(CollUtil.isNotEmpty(userIds), MtOrder::getUserId, userIds)
                .like(StrUtil.isNotBlank(obj.getOrderNo()), MtOrder::getOrderNo, obj.getOrderNo())
                .eq(ObjectUtil.isNotNull(obj.getRefundStatus()), MtOrder::getRefundStatus, obj.getRefundStatus())
                .eq(ObjectUtil.isNotNull(obj.getIsEvaluate()), MtOrder::getIsEvaluate, obj.getIsEvaluate())
                .eq(ObjectUtil.isNotNull(obj.getOrderFrom()), MtOrder::getOrderFrom, obj.getOrderFrom())
                .eq(ObjectUtil.isNotNull(obj.getShopId()), MtOrder::getShopId, obj.getShopId())
                .eq(ObjectUtil.isNotNull(obj.getUserId()), MtOrder::getUserId, obj.getUserId())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), MtOrder::getPayTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), MtOrder::getCreateTime));
        List<MtOrder> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            ShopOrderVo newsVo = new ShopOrderVo();
            BeanUtil.copyProperties(e, newsVo);
            //查询
            MtShopping mtShopping = mtShoppingMapper.selectById(e.getShopId());
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            newsVo.setUserMobile(ObjectUtil.isNotNull(dogUser) ? dogUser.getUserMobile() : "");
            newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
            //查询子项
            List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, e.getId()).orderByDesc(MtOrderGoods::getCreateTime));
            List<AdminOrderGoodsVo> newList = list.stream().map(f -> {
                AdminOrderGoodsVo adminOrderGoodsVo = new AdminOrderGoodsVo();
                MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
                MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
                adminOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
                adminOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
                adminOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
                return adminOrderGoodsVo;
            }).collect(Collectors.toList());
            //   List<AdminOrderGoodsVo> newList = mapperFacade.mapAsList(list, AdminOrderGoodsVo.class);
            newsVo.setAdminOrderGoodsVo(newList);
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 分页订单列表API用户
     * @Param: OrderFromDto
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<ApiShopOrderVo> getApiPageList(PageParam page, ApiShopOrderFromDto obj) {

        IPage iPage = this.page(page, Wrappers.<MtOrder>lambdaQuery()
                .like(StrUtil.isNotBlank(obj.getOrderNo()), MtOrder::getOrderNo, obj.getOrderNo())
                .eq(ObjectUtil.isNotNull(obj.getRefundStatus()), MtOrder::getRefundStatus, obj.getRefundStatus())
                .eq(ObjectUtil.isNotNull(obj.getIsEvaluate()), MtOrder::getIsEvaluate, obj.getIsEvaluate())
                .eq(MtOrder::getUserId, SecurityUtils.getUser().getUserId())
                .eq(ObjectUtil.isNotNull(obj.getOrderFrom()), MtOrder::getOrderFrom, obj.getOrderFrom())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), MtOrder::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), MtOrder::getCreateTime));
        List<MtOrder> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            ApiShopOrderVo newsVo = new ApiShopOrderVo();
            BeanUtil.copyProperties(e, newsVo);
            //查询
            MtShopping mtShopping = mtShoppingMapper.selectById(e.getShopId());
            newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            //查询子项
            List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, e.getId()).orderByDesc(MtOrderGoods::getCreateTime));
            List<ApiOrderGoodsVo> newList = list.stream().map(f -> {
                ApiOrderGoodsVo apiOrderGoodsVo = new ApiOrderGoodsVo();
                BeanUtil.copyProperties(f, apiOrderGoodsVo);
                MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
                MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
                apiOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
                apiOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
                apiOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
                return apiOrderGoodsVo;
            }).collect(Collectors.toList());
            //   List<ApiOrderGoodsVo> newList = mapperFacade.mapAsList(list, ApiOrderGoodsVo.class);
            newsVo.setApiOrderGoodsVo(newList);
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 分页订单列表API用户
     * @Param: OrderFromDto
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<ApiShopOrderVo> getApiSjPageList(PageParam page, ApiShopOrderFromDto obj) {

        //获取当前用户的店铺ID
        List<MtShopping> shopList = mtShoppingMapper.selectList(Wrappers.<MtShopping>lambdaQuery().eq(MtShopping::getStatus, 1).eq(MtShopping::getUserId, SecurityUtils.getUser().getUserId()).orderByDesc(MtShopping::getCreateTime));
        Validator.validateTrue(CollUtil.isNotEmpty(shopList), "该用户还不是商家");
        IPage iPage = this.page(page, Wrappers.<MtOrder>lambdaQuery()
                .like(StrUtil.isNotBlank(obj.getOrderNo()), MtOrder::getOrderNo, obj.getOrderNo())
                .eq(ObjectUtil.isNotNull(obj.getRefundStatus()), MtOrder::getRefundStatus, obj.getRefundStatus())
                .eq(ObjectUtil.isNotNull(obj.getIsEvaluate()), MtOrder::getIsEvaluate, obj.getIsEvaluate())
                .eq(ObjectUtil.isNotNull(obj.getOrderFrom()), MtOrder::getOrderFrom, obj.getOrderFrom())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), MtOrder::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .eq(MtOrder::getShopId, shopList.get(0).getId())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), MtOrder::getCreateTime));
        List<MtOrder> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            ApiShopOrderVo newsVo = new ApiShopOrderVo();
            BeanUtil.copyProperties(e, newsVo);
            //查询
            MtShopping mtShopping = mtShoppingMapper.selectById(e.getShopId());
            newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            //查询子项
            List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, e.getId()).orderByDesc(MtOrderGoods::getCreateTime));
            List<ApiOrderGoodsVo> newList = list.stream().map(f -> {
                ApiOrderGoodsVo apiOrderGoodsVo = new ApiOrderGoodsVo();
                BeanUtil.copyProperties(f, apiOrderGoodsVo);
                MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
                MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
                apiOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
                apiOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
                apiOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
                return apiOrderGoodsVo;
            }).collect(Collectors.toList());
            newsVo.setApiOrderGoodsVo(newList);
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 获取商家的经营数据
     * @Param: CashWithdrawalAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    public ApiSjDataVo getApiSjJyObj(ApiSjDataFromDto obj) {
        //获取当前用户的店铺ID
        List<MtShopping> shopList = mtShoppingMapper.selectList(Wrappers.<MtShopping>lambdaQuery().eq(MtShopping::getStatus, 1).eq(MtShopping::getUserId, SecurityUtils.getUser().getUserId()).orderByDesc(MtShopping::getCreateTime));
        Validator.validateTrue(CollUtil.isNotEmpty(shopList), "该用户还不是商家");
        Long shopId = shopList.get(0).getId();
        Long startTime = ToolUtil.dateSecond(DateUtil.beginOfDay(DateUtil.date()));
        Long endTime = ToolUtil.dateSecond(DateUtil.endOfDay(DateUtil.date()));
        if (ObjectUtil.isNotNull(obj.getType())) {
            if (obj.getType() == 0) {
                startTime = ToolUtil.dateSecond(DateUtil.beginOfMonth(DateUtil.date()));
                endTime = ToolUtil.dateSecond(DateUtil.endOfMonth(DateUtil.date()));
            } else if (obj.getType() == 1) {
                startTime = ToolUtil.dateSecond(DateUtil.beginOfYear(DateUtil.date()));
                endTime = ToolUtil.dateSecond(DateUtil.endOfYear(DateUtil.date()));
            } else {
                Validator.validateTrue(ObjectUtil.isNotNull(obj.getStartTime()), "开始时间不能为空!");
                Validator.validateTrue(ObjectUtil.isNotNull(obj.getEndTime()), "结束时间不能为空!");
                startTime = obj.getStartTime();
                endTime = obj.getEndTime();
            }
        }
        ApiSjDataVo newsVo = new ApiSjDataVo();
        newsVo.setSumMoney(this.baseMapper.getMoney(1, shopId, startTime, endTime));
        newsVo.setPayMoney(this.baseMapper.getsr(8, shopId, startTime, endTime));
        newsVo.setNum(this.count(Wrappers.<MtOrder>lambdaQuery().eq(MtOrder::getOrderStatus, 1).eq(MtOrder::getShopId, shopId).between(MtOrder::getCreateTime, startTime, endTime)));
        return newsVo;
    }

    /**
     * @Description: 订单详情 app
     * @Param: CashWithdrawalAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    public ApiShopOrderXqVo getApiObjXq(Long id) {
        //订单
        MtOrder mtOrder = this.getById(id);
        Validator.validateNotNull(mtOrder, "订单不存在");
        ApiShopOrderXqVo newsVo = new ApiShopOrderXqVo();
        BeanUtil.copyProperties(mtOrder, newsVo);
        if (StrUtil.isNotBlank(mtOrder.getRefundImgs()) && !mtOrder.getRefundImgs().equals("-1")) {
            List<String> ts = null;
            try {
                //ts = JSONUtil.toBean(e.getFeedbackImgArray(), ArrayList.class);
                ts = Json.parseArray(mtOrder.getRefundImgs(), String[].class);
            } catch (Exception ex) {
                ts = CollUtil.newArrayList();
            }
            newsVo.setRefundImgs(ts);
        }
        //查询
        MtShopping mtShopping = mtShoppingMapper.selectById(mtOrder.getShopId());
        newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
        newsVo.setTime(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getTime() : 30);
        DogUser dogUser = dogUserMapper.selectById(mtOrder.getUserId());
        newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
        //查询子项
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, mtOrder.getId()).orderByDesc(MtOrderGoods::getCreateTime));
        List<ApiOrderGoodsVo> newList = list.stream().map(f -> {
            ApiOrderGoodsVo apiOrderGoodsVo = new ApiOrderGoodsVo();
            BeanUtil.copyProperties(f, apiOrderGoodsVo);
            MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
            apiOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            apiOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
            apiOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
            return apiOrderGoodsVo;
        }).collect(Collectors.toList());
        newsVo.setApiOrderGoodsVo(newList);
        //查询地址
        //查询收货地址
        MtUserAddrOrder mtUserAddrOrder = mtUserAddrOrderMapper.selectById(mtOrder.getAddrOrderId());
        ApiUserAddrOrderVo apiUserAddrOrder = new ApiUserAddrOrderVo();
        BeanUtil.copyProperties(mtUserAddrOrder, apiUserAddrOrder);
        newsVo.setApiUserAddrOrderVo(apiUserAddrOrder);
        return newsVo;

    }

    /**
     * @Description: 订单详情通过订单编号
     * @Param: CashWithdrawalAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    public ApiShopOrderXqVo getApiObjByOrderNoXq(String orderNo) {
        //订单
        List<MtOrder> mtOrderList = this.list(Wrappers.<MtOrder>lambdaQuery().eq(MtOrder::getOrderNo, orderNo).orderByDesc(MtOrder::getCreateTime));
        Validator.validateTrue(CollUtil.isNotEmpty(mtOrderList), "订单不存在");
        ApiShopOrderXqVo newsVo = new ApiShopOrderXqVo();
        MtOrder mtOrder = mtOrderList.get(0);
        BeanUtil.copyProperties(mtOrder, newsVo);
        if (StrUtil.isNotBlank(mtOrder.getRefundImgs()) && !mtOrder.getRefundImgs().equals("-1")) {
            List<String> ts = null;
            try {
                //ts = JSONUtil.toBean(e.getFeedbackImgArray(), ArrayList.class);
                ts = Json.parseArray(mtOrder.getRefundImgs(), String[].class);
            } catch (Exception ex) {
                ts = CollUtil.newArrayList();
            }
            newsVo.setRefundImgs(ts);
        }
        //查询
        MtShopping mtShopping = mtShoppingMapper.selectById(mtOrder.getShopId());
        newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
        newsVo.setTime(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getTime() : 30);
        DogUser dogUser = dogUserMapper.selectById(mtOrder.getUserId());
        newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
        //查询子项
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, mtOrder.getId()).orderByDesc(MtOrderGoods::getCreateTime));
        List<ApiOrderGoodsVo> newList = list.stream().map(f -> {
            ApiOrderGoodsVo apiOrderGoodsVo = new ApiOrderGoodsVo();
            BeanUtil.copyProperties(f, apiOrderGoodsVo);
            MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
            apiOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            apiOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
            apiOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
            return apiOrderGoodsVo;
        }).collect(Collectors.toList());
        newsVo.setApiOrderGoodsVo(newList);
        //查询地址
        //查询收货地址
        MtUserAddrOrder mtUserAddrOrder = mtUserAddrOrderMapper.selectById(mtOrder.getAddrOrderId());
        ApiUserAddrOrderVo apiUserAddrOrder = new ApiUserAddrOrderVo();
        BeanUtil.copyProperties(mtUserAddrOrder, apiUserAddrOrder);
        newsVo.setApiUserAddrOrderVo(apiUserAddrOrder);
        return newsVo;

    }

    /**
     * @Description: 订单详情 后台
     * @Param: CashWithdrawalAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    public AdminShopOrderXqVo getObjXq(Long id) {
        //订单
        MtOrder mtOrder = this.getById(id);
        Validator.validateNotNull(mtOrder, "订单不存在");
        AdminShopOrderXqVo newsVo = new AdminShopOrderXqVo();
        BeanUtil.copyProperties(mtOrder, newsVo);
        if (StrUtil.isNotBlank(mtOrder.getRefundImgs()) && !mtOrder.getRefundImgs().equals("-1")) {
            List<String> ts = null;
            try {
                //ts = JSONUtil.toBean(e.getFeedbackImgArray(), ArrayList.class);
                ts = Json.parseArray(mtOrder.getRefundImgs(), String[].class);
            } catch (Exception ex) {
                ts = CollUtil.newArrayList();
            }
            newsVo.setRefundImgs(ts);
        }
        //查询
        MtShopping mtShopping = mtShoppingMapper.selectById(mtOrder.getShopId());
        newsVo.setShopName(ObjectUtil.isNotNull(mtShopping) ? mtShopping.getName() : "");
        DogUser dogUser = dogUserMapper.selectById(mtOrder.getUserId());
        newsVo.setUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
        //查询子项
        //查询子项
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, mtOrder.getId()).orderByDesc(MtOrderGoods::getCreateTime));
        List<AdminOrderGoodsVo> newList = list.stream().map(f -> {
            AdminOrderGoodsVo apiOrderGoodsVo = new AdminOrderGoodsVo();
            BeanUtil.copyProperties(f, apiOrderGoodsVo);
            MtGoods mtGoods = mtGoodsMapper.selectById(f.getGoodsId());
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(f.getSkuId());
            apiOrderGoodsVo.setGoodsName(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getName() : "");
            apiOrderGoodsVo.setPicture(ObjectUtil.isNotNull(mtGoods) ? mtGoods.getPicture() : "");
            apiOrderGoodsVo.setSkuName(ObjectUtil.isNotNull(mtGoodsSku) ? mtGoodsSku.getName() : "");
            return apiOrderGoodsVo;
        }).collect(Collectors.toList());
        newsVo.setAdminOrderGoodsVo(newList);
        //查询地址
        //查询收货地址
        MtUserAddrOrder mtUserAddrOrder = mtUserAddrOrderMapper.selectById(mtOrder.getAddrOrderId());
        AdminUserAddrOrderVo apiUserAddrOrder = new AdminUserAddrOrderVo();
        BeanUtil.copyProperties(mtUserAddrOrder, apiUserAddrOrder);
        newsVo.setAdminUserAddrOrderVo(apiUserAddrOrder);
        return newsVo;

    }

    /**
     * @Description: 增加订单(商品的)单商品直接下单
     * @Param: OrderAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @SneakyThrows
    public ApiOrderPrepayVo saveObj(ApiShopOrderAddDto obj) {

        Validator.validateTrue(obj.getNum() > 0, "数量不正确!");
        //判断商品是否存在
        MtGoods mtGoods = mtGoodsMapper.selectById(obj.getGoodId());
        Validator.validateNotNull(mtGoods, "商品不存在!");
        //查询订单
        MtOrder dogOrder = new MtOrder();
        BeanUtil.copyProperties(obj, dogOrder);
        dogOrder.setShopId(mtGoods.getShopId());
        dogOrder.setOrderNo(serialNumberUtils.serialNumberGenerate().toString());
        dogOrder.setOutTradeNo(serialNumberUtils.serialNumberGenerate().toString());
        dogOrder.setUserId(SecurityUtils.getUser().getUserId());
        BigDecimal couponMoney = BigDecimal.ZERO;
        BigDecimal orderMoney = BigDecimal.ZERO;
        BigDecimal price = BigDecimal.ZERO;
        MtGoodsSku mtGoodsSku = null;
        //判断商品总价
        //判断SKU是否存在
        mtGoodsSku = mtGoodsSkuMapper.selectById(obj.getSkuId());
        Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
        Validator.validateTrue(mtGoodsSku.getStock() > 0, "商品库存数量不足!");
        //判断库存是否充足
        Validator.validateTrue(mtGoodsSku.getStock() >= obj.getNum(), "商品库存数量不足!");
        //减少库存
        mtGoodsSku.setStock(mtGoodsSku.getStock() - obj.getNum());
        Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存减少失败!");
        orderMoney = mtGoodsSku.getPrice().multiply(BigDecimal.valueOf(obj.getNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
        price = mtGoodsSku.getPrice();
        //判断优惠券
        if (ObjectUtil.isNotNull(obj.getCouponId())) {
            MtCoupon mtCoupon = mtCouponMapper.selectById(obj.getCouponId());
            Validator.validateNotNull(mtCoupon, "优惠券不存在!");
            Validator.validateEqual(mtCoupon.getStatus(), 1, "优惠券已使用或者已经过期");
            //判断优惠金额能否使用
            if (orderMoney.compareTo(mtCoupon.getMinimumConsumption()) >= 0) {
                mtCoupon.setStatus(2);
                mtCoupon.setUpdateBy(SecurityUtils.getUser().getUserId());
                mtCoupon.setUpdateTime(DateUtil.currentSeconds());
                Validator.validateTrue(retBool(mtCouponMapper.updateById(mtCoupon)), "优惠券修改失败!");
                couponMoney = mtCoupon.getMoney();
                dogOrder.setCouponId(mtCoupon.getId());
            }
        }
        dogOrder.setOrderType(1);
        dogOrder.setOrderMoney(orderMoney);
        dogOrder.setCouponMoney(couponMoney);

        dogOrder.setPayMoney(dogOrder.getOrderMoney().subtract(couponMoney));
        if (dogOrder.getPayMoney().compareTo(BigDecimal.ZERO) <= 0) {
            dogOrder.setPayMoney(BigDecimal.ZERO);
        }
        dogOrder.setPayTime(DateUtil.currentSeconds());
        dogOrder.setCreateBy(SecurityUtils.getUser().getUserId());
        dogOrder.setCreateTime(DateUtil.currentSeconds());
        if (obj.getOrderFrom() == 0) {

            MtUserAddr mtUserAddr = mtUserAddrMapper.selectById(obj.getAddrId());
            Validator.validateNotNull(mtUserAddr, "地址不存在");
            //保存订单地址
            MtUserAddrOrder mtUserAddrOrder = new MtUserAddrOrder();
            BeanUtil.copyProperties(mtUserAddr, mtUserAddrOrder);
            mtUserAddrOrder.setId(IdWorker.getId());
            mtUserAddrOrder.setUserId(SecurityUtils.getUser().getUserId());
            mtUserAddrOrder.setCreateTime(DateUtil.currentSeconds());
            Validator.validateTrue(retBool(mtUserAddrOrderMapper.insert(mtUserAddrOrder)), "保存订单失败!");
            //更新订单地址
            dogOrder.setAddrOrderId(mtUserAddrOrder.getId());
        }

        Validator.validateTrue(this.save(dogOrder), "保存订单失败!");
        //保存订单子项
        MtOrderGoods mtOrderGoods = new MtOrderGoods();
        mtOrderGoods.setShopId(mtGoods.getShopId());
        mtOrderGoods.setOrderId(dogOrder.getId());
        mtOrderGoods.setOrderNo(dogOrder.getOrderNo());
        mtOrderGoods.setGoodsId(obj.getGoodId());
        mtOrderGoods.setSkuId(obj.getSkuId());
        mtOrderGoods.setPrice(price);
        mtOrderGoods.setNum(dogOrder.getNum());
        mtOrderGoods.setGoodsMoney(orderMoney);
        mtOrderGoods.setGoodsName(mtGoods.getName());
        mtOrderGoods.setSkuName(mtGoodsSku.getName());
        mtOrderGoods.setUserId(SecurityUtils.getUser().getUserId());
        mtOrderGoods.setGoodsType(mtGoods.getTypeId());
        mtOrderGoods.setCreateBy(SecurityUtils.getUser().getUserId());
        mtOrderGoods.setCreateTime(DateUtil.currentSeconds());
        Validator.validateTrue(retBool(mtOrderGoodsMapper.insert(mtOrderGoods)), "保存订单失败!");
        return this.getOrderPrepayVo(dogOrder, mtGoods.getName());
    }

    /**
     * @Description: 购物车直接下单
     * @Param: OrderAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public ApiOrderPrepayVo saveBasketObj(ApiOrderBasketAddDto obj) {
        MtOrder newObj = new MtOrder();
        newObj.setOrderType(1);
        //查询地址
        Validator.validateTrue(CollUtil.isNotEmpty(obj.getData()), "购物车信息没有填写!");
        List<ApiOrderBasketDataAddDto> list = obj.getData();
        String outTradeNo = serialNumberUtils.serialNumberGenerate().toString();
        newObj.setOutTradeNo(outTradeNo);
        BigDecimal payMoney = BigDecimal.ZERO;
        for (int j = 0; j < list.size(); j++) {
            ApiOrderBasketDataAddDto e = list.get(j);
            //查询订单
            MtOrder dogOrder = new MtOrder();
            BeanUtil.copyProperties(obj, dogOrder);
            dogOrder.setId(IdWorker.getId());
            dogOrder.setShopId(e.getShopId());
            dogOrder.setOrderNo(serialNumberUtils.serialNumberGenerate().toString());
            dogOrder.setOutTradeNo(outTradeNo);
            dogOrder.setUserId(SecurityUtils.getUser().getUserId());
            BigDecimal couponMoney = BigDecimal.ZERO;
            BigDecimal orderMoney = BigDecimal.ZERO;
            Integer num = 0;
            //判断购物车是否存在
            for (int i = 0; i < e.getBasketIds().size(); i++) {
                BigDecimal price = BigDecimal.ZERO;
                MtBasket mtBasket = mtBasketMapper.selectById(e.getBasketIds().get(i));
                Validator.validateNotNull(mtBasket, "购物车不存在!");
                MtGoods mtGoods = mtGoodsMapper.selectById(mtBasket.getGoodsId());
                Validator.validateNotNull(mtGoods, "商品已下架!");
                num = num + mtBasket.getBasketCount();
                //判断商品总价
                //判断SKU是否存在
                MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(mtBasket.getSkuId());
                Validator.validateNotNull(mtGoodsSku, "商品已下架!");
                Validator.validateTrue(mtGoodsSku.getStock() > 0, "商品库存数量不足!");
                //判断库存是否充足
                Validator.validateTrue(mtGoodsSku.getStock() >= mtBasket.getBasketCount(), "商品库存数量不足!");
                //减少库存
                mtGoodsSku.setStock(mtGoodsSku.getStock() - mtBasket.getBasketCount());
                Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存减少失败!");
                orderMoney = orderMoney.add(mtGoodsSku.getPrice().multiply(BigDecimal.valueOf(mtBasket.getBasketCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
                price = mtGoodsSku.getPrice();
                //保存订单子项
                MtOrderGoods mtOrderGoods = new MtOrderGoods();
                mtOrderGoods.setOrderId(dogOrder.getId());
                mtOrderGoods.setShopId(e.getShopId());
                mtOrderGoods.setOrderNo(dogOrder.getOrderNo());
                mtOrderGoods.setGoodsId(mtBasket.getGoodsId());
                mtOrderGoods.setGoodsName(mtGoods.getName());
                mtOrderGoods.setSkuName(mtGoodsSku.getName());
                mtOrderGoods.setSkuId(mtBasket.getSkuId());
                mtOrderGoods.setPrice(price);
                mtOrderGoods.setNum(mtBasket.getBasketCount());
                mtOrderGoods.setGoodsMoney(price.multiply(BigDecimal.valueOf(mtBasket.getBasketCount())).setScale(2, BigDecimal.ROUND_HALF_UP));
                mtOrderGoods.setUserId(SecurityUtils.getUser().getUserId());
                mtOrderGoods.setGoodsType(mtGoods.getTypeId());
                mtOrderGoods.setCreateBy(SecurityUtils.getUser().getUserId());
                mtOrderGoods.setCreateTime(DateUtil.currentSeconds());
                Validator.validateTrue(retBool(mtOrderGoodsMapper.insert(mtOrderGoods)), "保存订单失败!");
            }
            //判断优惠券
            if (ObjectUtil.isNotNull(e.getCouponId())) {
                MtCoupon mtCoupon = mtCouponMapper.selectById(e.getCouponId());
                Validator.validateNotNull(mtCoupon, "优惠券不存在!");
                Validator.validateEqual(mtCoupon.getStatus(), 1, "优惠券已使用或者已经过期");
                //判断优惠金额能否使用
                if (orderMoney.compareTo(mtCoupon.getMinimumConsumption()) >= 0) {
                    mtCoupon.setStatus(2);
                    mtCoupon.setUpdateBy(SecurityUtils.getUser().getUserId());
                    mtCoupon.setUpdateTime(DateUtil.currentSeconds());
                    Validator.validateTrue(retBool(mtCouponMapper.updateById(mtCoupon)), "优惠券修改失败!");
                    couponMoney = mtCoupon.getMoney();
                    dogOrder.setCouponId(mtCoupon.getId());
                }
            }
            dogOrder.setOrderType(1);
            dogOrder.setOrderMoney(orderMoney);
            dogOrder.setCouponMoney(couponMoney);
            dogOrder.setPayMoney(dogOrder.getOrderMoney().subtract(couponMoney));
            if (dogOrder.getPayMoney().compareTo(BigDecimal.ZERO) <= 0) {
                dogOrder.setPayMoney(BigDecimal.ZERO);
            }
            dogOrder.setNum(num);
            dogOrder.setPayTime(DateUtil.currentSeconds());
            dogOrder.setCreateBy(SecurityUtils.getUser().getUserId());
            dogOrder.setCreateTime(DateUtil.currentSeconds());
            if (obj.getOrderFrom() == 0) {
                MtUserAddr mtUserAddr = mtUserAddrMapper.selectById(obj.getAddrId());
                Validator.validateNotNull(mtUserAddr, "地址不存在");
                //保存订单地址
                MtUserAddrOrder mtUserAddrOrder = new MtUserAddrOrder();
                BeanUtil.copyProperties(mtUserAddr, mtUserAddrOrder);
                mtUserAddrOrder.setId(IdWorker.getId());
                mtUserAddrOrder.setUserId(SecurityUtils.getUser().getUserId());
                mtUserAddrOrder.setCreateTime(DateUtil.currentSeconds());
                Validator.validateTrue(retBool(mtUserAddrOrderMapper.insert(mtUserAddrOrder)), "保存订单失败!");
                //更新订单地址
                dogOrder.setAddrOrderId(mtUserAddrOrder.getId());
            }

            Validator.validateTrue(this.save(dogOrder), "保存订单失败!");
            //删除购物车
            Validator.validateTrue(retBool(mtBasketMapper.deleteBatchIds(e.getBasketIds())), "移除购物车失败!");
            payMoney = payMoney.add(dogOrder.getPayMoney());
        }
        newObj.setPayMoney(payMoney);
        return this.getOrderPrepayVo(newObj, "购物车直接购买");

    }

    /**
     * @Description: 取消订单
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        MtOrder mtOrder = this.getById(id);
        Validator.validateNotNull(mtOrder, "订单不存在!");
        Validator.validateEqual(mtOrder.getOrderStatus(), 0, "只有未支付可以取消订单!");
        mtOrder.setRefundStatus(5);
        mtOrder.setUpdateBy(SecurityUtils.getUser().getUserId());
        mtOrder.setUpdateTime(DateUtil.currentSeconds());
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, mtOrder.getId()));
        list.forEach(e -> {
            //判断商品是否存在
            MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
            Validator.validateNotNull(mtGoods, "商品不存在!");
            //判断SKU是否存在
            MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(e.getSkuId());
            Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");
            //增加库存
            mtGoodsSku.setStock(mtGoodsSku.getStock() + e.getNum());
            Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存增加失败!");
        });
        //返回优惠券
        if (ObjectUtil.isNotNull(mtOrder.getCouponId()) && mtOrder.getCouponId() != -1L) {
            MtCoupon mtCoupon = mtCouponMapper.selectById(mtOrder.getCouponId());
            Validator.validateNotNull(mtCoupon, "优惠券不存在!");
            mtCoupon.setStatus(1);
            mtCoupon.setUpdateBy(SecurityUtils.getUser().getUserId());
            mtCoupon.setUpdateTime(DateUtil.currentSeconds());
            Validator.validateTrue(retBool(mtCouponMapper.updateById(mtCoupon)), "优惠券修改失败!");
        }
        Validator.validateTrue(this.updateById(mtOrder), "优惠券修改失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 小程序微信 Order订单 - 支付回调
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @SneakyThrows
    public Boolean wxMiniPayLowerOrderCallback(String xmData) {
        // 解析
        WxPayOrderNotifyResult wxPayOrderNotifyResult = weChatMiniService.parseOrderNotifyResult(xmData);
        // 判断是否支付成功
        if (wxPayOrderNotifyResult.getReturnCode().equals("SUCCESS") && wxPayOrderNotifyResult.getResultCode()
                .equals("SUCCESS")) {
            String outTradeNo = wxPayOrderNotifyResult.getOutTradeNo();
            return paymentResultVerification(outTradeNo);
        }
        return false;
    }

    /**
     * @Description: 申请退款
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyreFund(ApiOrderRefundAddDto obj) {
        MtOrder order = this.getById(obj.getOrderId());
        Validator.validateNotNull(order, "订单信息不存在");
        order.setRefundStatus(2);
        order.setRefundReason(obj.getRefundReason());
        order.setRefundImgs(JSONUtil.toJsonStr(obj.getRefundImgs()));
        order.setRefundRemarks(obj.getRefundRemarks());
        Validator.validateTrue(this.updateById(order), "申请退款失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 支付结果的校验
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean paymentResultVerification(String outTradeNo) {
        //判断订单是否存在
        List<MtOrder> list = this.list(Wrappers.<MtOrder>lambdaQuery().eq(MtOrder::getOutTradeNo, outTradeNo));
        Validator.validateTrue(CollUtil.isNotEmpty(list), "订单不存在");
        list.forEach(e -> {
            //修改订单状态
            e.setOrderStatus(1);
            if (e.getOrderFrom() == 0) {
                e.setRefundStatus(6);
                e.setShippingStatus(0);
            } else {
                e.setRefundStatus(7);
                e.setShippingStatus(2);
            }

            e.setUpdateTime(DateUtil.currentSeconds());
            Validator.validateTrue(this.updateById(e), "支付回调失败!");
            //给商家发短信
            MtShopping mtShopping = mtShoppingMapper.selectById(e.getShopId());
            if (ObjectUtil.isNotNull(mtShopping)) {
                if (Validator.isMobile(mtShopping.getMobile())) {
                    mobileService.sendOrderSms(mtShopping.getMobile(),mtShopping.getUserId());
                }
            }
        });

        //修改商品的销售数量
        //修改店铺的销售数量
        return Boolean.TRUE;
    }

    /**
     * @Description: 返回下单实体
     * @Param: ids
     * @return: OrderPrepayVo
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    public ApiOrderPrepayVo getOrderPrepayVo(MtOrder order, String goodsName) {
        List<DogUserConnect> list = dogUserConnectMapper.selectList(Wrappers.<DogUserConnect>lambdaQuery().eq(DogUserConnect::getUserId, SecurityUtils.getUser().getUserId()));
        Validator.validateTrue(CollUtil.isNotEmpty(list), "用户未绑定微信不能付款");
        DogUserConnect dogUserConnect = list.get(0);
        ApiOrderPrepayVo orderPrepayVo = new ApiOrderPrepayVo();
        //公众号
        if (order.getOrderType() == 0) {
            orderPrepayVo.setOpenid(dogUserConnect.getGzhOpenid());
        } else {
            orderPrepayVo.setOpenid(dogUserConnect.getMiniShopOpenid());
        }
        orderPrepayVo.setOrderId(order.getId());
        orderPrepayVo.setOrderNo(order.getOutTradeNo());
        orderPrepayVo.setHnrbMoney(order.getPayMoney());
        orderPrepayVo.setProName(goodsName);
        orderPrepayVo.setOrderType(2);
        return orderPrepayVo;
    }

    /**
     * @Description: 确认退款(pc)
     * @Param: OrderFromDto
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public Boolean editOrderInfoFund(ApiOrderRefundEditDto obj) {

        MtOrder order = this.getById(obj.getOrderId());
        Validator.validateNotNull(order, "订单信息不存在");
        Validator.validateEqual(order.getRefundStatus(), 2, "只有申请退款的才能操作!");
        if (obj.getRefundStatus() == 3) {
            order.setRefundStatus(3);
            Validator.validateTrue(this.updateById(order), "退款拒绝失败!");
            return Boolean.TRUE;
        } else {
            WxPayRefundResult wxpayrefundresult = new WxPayRefundResult();
            AlipayTradeRefundResponse alipayTradeRefundResponse = new AlipayTradeRefundResponse();
            //设置退款信息
            WxPayRefundRequest wxpayrefundrequest = new WxPayRefundRequest();
            //设备标识
            //wxpayrefundrequest.setDeviceInfo(orderinfoentity.getDeviceId());
            //商户订单号
            wxpayrefundrequest.setOutTradeNo(order.getOutTradeNo());
            //商户退款单号
            wxpayrefundrequest.setOutRefundNo(order.getOutTradeNo());
            //订单金额
            wxpayrefundrequest.setTotalFee(order.getPayMoney().multiply(BigDecimal.valueOf(100)).intValue());
            //退款金额
            wxpayrefundrequest.setRefundFee(order.getPayMoney().multiply(BigDecimal.valueOf(100)).intValue());
            //微信小程序预支付
            wxpayrefundresult = weChatMiniService.refund(wxpayrefundrequest);
            //调微信支付
            System.out.println(JSONUtil.toJsonStr(alipayTradeRefundResponse));
            if ((wxpayrefundresult.getReturnCode().equals("SUCCESS") && wxpayrefundresult.getResultCode().equals("SUCCESS"))
                    || (StrUtil.equals(alipayTradeRefundResponse.getMsg(), "Success") && StrUtil
                    .equals(alipayTradeRefundResponse.getFundChange(), "Y"))) {
                order.setOrderStatus(5);
                order.setUpdateTime(DateUtil.currentSeconds());
                List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, order.getId()));
                list.forEach(e -> {
                    //判断商品是否存在
                    MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
                    // Validator.validateNotNull(mtGoods, "商品不存在!");
                    //判断SKU是否存在
                    MtGoodsSku mtGoodsSku = mtGoodsSkuMapper.selectById(e.getSkuId());
                    if (ObjectUtil.isNotNull(mtGoodsSku)) {
                        //增加库存
                        mtGoodsSku.setStock(mtGoodsSku.getStock() + e.getNum());
                        Validator.validateTrue(retBool(mtGoodsSkuMapper.updateById(mtGoodsSku)), "库存增加失败!");
                    }
                    //   Validator.validateNotNull(mtGoodsSku, "商品sku不存在!");


                });
                //返回优惠券
                if (ObjectUtil.isNotNull(order.getCouponId())) {
                    MtCoupon mtCoupon = mtCouponMapper.selectById(order.getCouponId());
                    if (ObjectUtil.isNotNull(mtCoupon)) {
                        mtCoupon.setStatus(1);
                        mtCoupon.setUpdateBy(SecurityUtils.getUser().getUserId());
                        mtCoupon.setUpdateTime(DateUtil.currentSeconds());
                        Validator.validateTrue(retBool(mtCouponMapper.updateById(mtCoupon)), "优惠券修改失败!");
                    }
                    //  Validator.validateNotNull(mtCoupon, "优惠券不存在!");

                }
                order.setRefundStatus(4);
                Validator.validateTrue(this.updateById(order), "退款失败!");
                //查询店铺账号
                List<MtShoppingAccount> list1 = mtShoppingAccountMapper.selectList(Wrappers.<MtShoppingAccount>lambdaQuery().eq(MtShoppingAccount::getShopId, order.getShopId()).orderByDesc(MtShoppingAccount::getCreateTime));
                //  Validator.validateTrue(CollUtil.isNotEmpty(list1), "店铺信息不完善");
                if (CollUtil.isNotEmpty(list1)) {
                    //开始流水
                    MtShoppingAccount mtShoppingAccount = list1.get(0);
                    mtShoppingAccount.setMoney(mtShoppingAccount.getMoney().subtract(order.getPayMoney()));
                    mtShoppingAccount.setUpdateTime(DateUtil.currentSeconds());
                    Validator.validateTrue(retBool(mtShoppingAccountMapper.updateById(mtShoppingAccount)), "店铺增加余额失败!");
                    //支付记录流水(用户)
                    MtFlowingWater mtFlowingWater = new MtFlowingWater();
                    mtFlowingWater.setSerialNo(order.getOrderNo());
                    mtFlowingWater.setWaterUserId(order.getUserId());
                    mtFlowingWater.setWaterShopId(order.getShopId());
                    mtFlowingWater.setWaterMoney(order.getPayMoney());
                    mtFlowingWater.setWaterType(0);
                    mtFlowingWater.setWaterAccount(0);
                    mtFlowingWater.setInoutType(1);
                    mtFlowingWater.setWaterExplain("用户退款");
                    mtFlowingWater.setCreateTime(DateUtil.currentSeconds());
                    mtFlowingWater.setCreateBy(order.getUserId());
                    Validator.validateTrue(retBool(mtFlowingWaterMapper.insert(mtFlowingWater)), "用户流水增加失败!");
                    MtFlowingWater mtFlowingWater1 = new MtFlowingWater();
                    mtFlowingWater1.setSerialNo(order.getOrderNo());
                    mtFlowingWater1.setWaterUserId(order.getUserId());
                    mtFlowingWater1.setWaterShopId(order.getShopId());
                    mtFlowingWater1.setWaterMoney(order.getPayMoney().negate());
                    mtFlowingWater1.setWaterType(1);
                    mtFlowingWater1.setWaterAccount(0);
                    mtFlowingWater1.setInoutType(5);
                    mtFlowingWater1.setWaterExplain("店铺退款");
                    mtFlowingWater1.setCreateTime(DateUtil.currentSeconds());
                    mtFlowingWater1.setCreateBy(order.getUserId());
                    Validator.validateTrue(retBool(mtFlowingWaterMapper.insert(mtFlowingWater1)), "用户流水增加失败!");

                }


                return Boolean.TRUE;
            }

            return Boolean.FALSE;
        }

    }

    /**
     * @Description: 确认收货
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    public Boolean conOrder(Long orderId) {
        MtOrder order = this.getById(orderId);
        Validator.validateNotNull(order, "订单信息不存在");
        if (order.getOrderFrom() == 0) {
            Validator.validateEqual(order.getRefundStatus(), 7, "只有待收货可以确认收获!");
        }

        order.setRefundStatus(8);
        order.setShippingStatus(3);
        order.setFinishTime(DateUtil.currentSeconds());
        //修改订单子项
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, order.getId()));
        list.forEach(e -> {
                    e.setShippingStatus(3);
                    Validator.validateTrue(retBool(mtOrderGoodsMapper.updateById(e)), "确认收货失败!");
                    //商品销售数量增加
                    MtGoods mtGoods = mtGoodsMapper.selectById(e.getGoodsId());
                    if (ObjectUtil.isNotNull(mtGoods)) {
                        mtGoods.setSales(mtGoods.getSales() + e.getNum());
                        Validator.validateTrue(retBool(mtGoodsMapper.updateById(mtGoods)), "修改商品失败!");
                    }
                    MtShopping mtShopping = mtShoppingMapper.selectById(e.getShopId());
                    if (ObjectUtil.isNotNull(mtShopping)) {
                        mtShopping.setSales(mtShopping.getSales() + e.getNum());
                        Validator.validateTrue(retBool(mtShoppingMapper.updateById(mtShopping)), "修改店铺失败!");
                    }
                }
        );
        Validator.validateTrue(this.updateById(order), "确认收货失败!");

        //查询店铺账号
        List<MtShoppingAccount> list1 = mtShoppingAccountMapper.selectList(Wrappers.<MtShoppingAccount>lambdaQuery().eq(MtShoppingAccount::getShopId, order.getShopId()).orderByDesc(MtShoppingAccount::getCreateTime));
        Validator.validateTrue(CollUtil.isNotEmpty(list1), "店铺信息不完善");
        //开始流水
        MtShoppingAccount mtShoppingAccount = list1.get(0);
        MtShopping mtShopping = mtShoppingMapper.selectById(order.getShopId());
        Validator.validateNotNull(mtShopping, "店铺不存在!");
        BigDecimal shopMoney = order.getPayMoney().multiply(mtShopping.getBl()).setScale(2, BigDecimal.ROUND_HALF_UP);
        mtShoppingAccount.setMoney(mtShoppingAccount.getMoney().add(shopMoney));
        mtShoppingAccount.setUpdateTime(DateUtil.currentSeconds());
        Validator.validateTrue(retBool(mtShoppingAccountMapper.updateById(mtShoppingAccount)), "店铺增加余额失败!");
        //支付记录流水(用户)
        MtFlowingWater mtFlowingWater = new MtFlowingWater();
        mtFlowingWater.setSerialNo(order.getOrderNo());
        mtFlowingWater.setWaterUserId(order.getUserId());
        mtFlowingWater.setWaterShopId(order.getShopId());
        mtFlowingWater.setWaterMoney(order.getPayMoney().negate());
        mtFlowingWater.setWaterType(0);
        mtFlowingWater.setWaterAccount(0);
        mtFlowingWater.setInoutType(0);
        mtFlowingWater.setWaterExplain("用户订单支付");
        mtFlowingWater.setCreateTime(DateUtil.currentSeconds());
        mtFlowingWater.setCreateBy(order.getUserId());
        Validator.validateTrue(retBool(mtFlowingWaterMapper.insert(mtFlowingWater)), "用户流水增加失败!");
        MtFlowingWater mtFlowingWater1 = new MtFlowingWater();
        mtFlowingWater1.setSerialNo(order.getOrderNo());
        mtFlowingWater1.setWaterUserId(order.getUserId());
        mtFlowingWater1.setWaterShopId(order.getShopId());
        mtFlowingWater1.setWaterMoney(shopMoney);
        mtFlowingWater1.setWaterType(1);
        mtFlowingWater1.setWaterAccount(0);
        mtFlowingWater1.setInoutType(3);
        mtFlowingWater1.setWaterExplain("订单结算");
        mtFlowingWater1.setCreateTime(DateUtil.currentSeconds());
        mtFlowingWater1.setCreateBy(order.getUserId());
        Validator.validateTrue(retBool(mtFlowingWaterMapper.insert(mtFlowingWater1)), "用户流水增加失败!");
        return Boolean.TRUE;
    }

    /**
     * 订单发货
     *
     * @param id
     * @return
     * @author fengjk
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendOrder(Long id) {
        MtOrder order = this.getById(id);
        Validator.validateNotNull(order, "订单信息不存在");
        Validator.validateEqual(order.getRefundStatus(), 6, "只有待发货可以发货!");
        order.setRefundStatus(7);
        order.setShippingStatus(2);
        //修改订单子项
        List<MtOrderGoods> list = mtOrderGoodsMapper.selectList(Wrappers.<MtOrderGoods>lambdaQuery().eq(MtOrderGoods::getOrderId, order.getId()));
        list.forEach(e -> {
                    e.setShippingStatus(2);

                    Validator.validateTrue(retBool(mtOrderGoodsMapper.updateById(e)), "确认收货失败!");
                }
        );
        Validator.validateTrue(this.updateById(order), "确认收货失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 是否在配送范围内
     * @Param: OrderAddDto
     * @return: R
     * @Author: wph
     * @Date:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sfSend(ApiShopOrderSendFromDto obj) {
        List<MtShopping> list = mtShoppingMapper.selectList(Wrappers.<MtShopping>lambdaQuery().in(MtShopping::getId, obj.getShopIds()).eq(MtShopping::getStatus, 1));
        Validator.validateTrue(CollUtil.isNotEmpty(list), "店铺不存在!");
        MtUserAddr mtUserAddr = mtUserAddrMapper.selectById(obj.getAddressId());
        Validator.validateNotNull(mtUserAddr, "收货地址不存在!");
        list.forEach(e -> {
            //计算距离
            GlobalCoordinates source = new GlobalCoordinates(e.getLatitude().doubleValue(), e.getLongitude().doubleValue());
            GlobalCoordinates target = new GlobalCoordinates(mtUserAddr.getLatitude(), mtUserAddr.getLongitude());
            BigDecimal distance = BigDecimal.valueOf(getDistanceMeter(source, target, Ellipsoid.Sphere)).divide(BigDecimal.valueOf(1000), 1, BigDecimal.ROUND_HALF_UP);
            Validator.validateTrue(distance.compareTo(e.getSendRange()) <= 0, e.getName() + "不在配送范围!");
        });

        return Boolean.TRUE;
    }

    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {

        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

        return geoCurve.getEllipsoidalDistance();
    }
}
